package com.wsjc.web.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.wsjc.web.config.RedisInitServers;
import com.wsjc.web.entity.Operate;
import com.wsjc.web.entity.RedisInfoDetail;
import com.wsjc.web.util.RedisUtil;

import redis.clients.jedis.JedisPool;
import redis.clients.util.Slowlog;

@Service
public class RedisService {
	
	@Autowired
	RedisUtil redisUtil;
	
	@Autowired
	RedisInitServers redisInitServers;
	
	/**
	 * 
	 * @param address  ip:port
	 * @return
	 */
	public RedisInfoDetail getRedisInfo(String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		
		//获取redis服务器信息
		String info = redisUtil.getRedisInfo(jedisPool);
//		List<RedisInfoDetail> ridList = new ArrayList<RedisInfoDetail>();
		String[] strs = info.split("\n");
		RedisInfoDetail rif = new RedisInfoDetail();
		if (strs != null && strs.length > 0) {
			for (int i = 0; i < strs.length; i++) {
				String s = strs[i];
				String[] str = s.split(":");
				if (str != null && str.length > 1) {
					String key = str[0];
					String value = str[1];
					
					if(key.equals("db0")) {
						str = value.split(",");
						str = str[0].split("=");
						key = str[0];
						value = str[1];
						rif.setValue(rif, key, value);
						continue;
					}
					rif.setValue(rif, key, value);
				}

			}
		}
		return rif;
	}
	
	//获取redis日志列表
	public List<Operate> getLogs(long entries, String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		
        List<Slowlog> list = redisUtil.getLogs(entries, jedisPool);
		List<Operate> opList = null;
		Operate op  = null;
		boolean flag = false;
		if (list != null && list.size() > 0) {
			opList = new LinkedList<Operate>();
			for (Slowlog sl : list) {
				String args = JSON.toJSONString(sl.getArgs());
				if (args.equals("[\"PING\"]") || args.equals("[\"SLOWLOG\",\"get\"]") || args.equals("[\"DBSIZE\"]") || args.equals("[\"INFO\"]")) {
					continue;
				}	
				op = new Operate();
				flag = true;
				op.setId(sl.getId());
				op.setExecuteTime(getDateStr(sl.getTimeStamp() * 1000));
				op.setUsedTime(sl.getExecutionTime()/1000.0 + "ms");
				op.setArgs(args);
				opList.add(op);
			}
		} 
		if (flag) 
			return opList;
		else 
			return null;
	}
	//获取日志总数
	public Long getLogLen(String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		return redisUtil.getLogsLen(jedisPool);
	}
	
	//清空日志
	public String logEmpty(String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		return redisUtil.logEmpty(jedisPool);
	}
	//获取当前数据库中key的数量
	public Map<String,Object> getKeysSize(String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		long dbSize = redisUtil.dbSize(jedisPool);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("create_time", new Date().getTime());
		map.put("dbSize", dbSize);
		return map;
	}
	
	//获取当前redis使用内存大小情况
	public Map<String,Object> getMemeryInfo(String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		String[] strs = redisUtil.useMemoryInfo(jedisPool).split("\n");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("time", new Date().getTime());
		for (int i = 0; i < strs.length; i++) {
			String s = strs[i];
			String[] detail = s.split(":");
			if (detail[0].equals("used_memory")) {
				map.put("used", detail[1].substring(0, detail[1].length() - 1));
			}
			if (detail[0].equals("used_memory_rss")) {
				map.put("rss", detail[1].substring(0, detail[1].length() - 1));
			}
		}
		return map;
	}
	
	private String getDateStr(long timeStmp) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return dateFormat.format(new Date(timeStmp));
	}
	
	//获取当前redis使用Cpu大小情况
	public Map<String,Object> getCpuInfo(String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		String[] strs = redisUtil.useCpuInfo(jedisPool).split("\n");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("time", new Date().getTime());
		for (int i = 0; i < strs.length; i++) {
			String s = strs[i];
			String[] detail = s.split(":");
			if (detail[0].equals("used_cpu_sys")) {
				map.put("sys", Double.valueOf(detail[1].substring(0, detail[1].length() - 1)));
			}
			if (detail[0].equals("used_cpu_user")) {
				map.put("user",   Double.valueOf(detail[1].substring(0, detail[1].length() - 1))  );
			}
		}
		return map;
	}

	//获取每秒执行命令数
	public Object getCmdInfo(String address) {
		
		JedisPool jedisPool = redisInitServers.getJedisPoll(address);
		String[] strs = redisUtil.useCmdInfo(jedisPool).split("\n");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("time", new Date().getTime());
		for (int i = 0; i < strs.length; i++) {
			String s = strs[i];
			String[] detail = s.split(":");
			if (detail[0].equals("instantaneous_ops_per_sec")) {
				map.put("cmd", Integer.valueOf(detail[1].substring(0, detail[1].length() - 1)));
			}
		}
		return map;
	}

	
	public List<String> getNodesInfo() {
		return redisInitServers.getNodesInfo();
	}
	
	
	//获取每秒执行命令数
	public String getStatus(String address) {
		String status = redisInitServers.getJedisStatus(address);
		return status;
	}
	
	
	
	
	
	
}
